package com.zfy.aclservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zfy.aclservice.entity.Permission;
import com.zfy.aclservice.entity.RolePermission;
import com.zfy.aclservice.entity.User;
import com.zfy.aclservice.helper.MenuHelper;
import com.zfy.aclservice.helper.PermissionHelper;
import com.zfy.aclservice.mapper.PermissionMapper;
import com.zfy.aclservice.service.PermissionService;
import com.zfy.aclservice.service.RolePermissionService;
import com.zfy.aclservice.service.UserRoleService;
import com.zfy.aclservice.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    //根据角色获取菜单
    @Override
    public List<Permission> selectAllMenu(String roleId) {
        //将id转换为整型再排序
        QueryWrapper<Permission> wrapper = new QueryWrapper<Permission>().orderByAsc("CAST(id AS SIGNED)");
        //获取全部菜单
        List<Permission> allPermissionList = this.list(wrapper);

        //根据角色id获取角色权限
        QueryWrapper<RolePermission> wrapper1 = new QueryWrapper<RolePermission>().eq("role_id", roleId);
        List<RolePermission> rolePermissionList = rolePermissionService.list(wrapper1);

        for (Permission allPermission : allPermissionList) {
            for (RolePermission rolePermission : rolePermissionList) {
                if (rolePermission.getPermissionId().equals(allPermission.getId()) &&
                        allPermission.getType() == 2) {
                    allPermission.setSelect(true);
                }
            }
        }

        List<Permission> permissionList = PermissionHelper.build(allPermissionList);
        System.out.println(permissionList);
//        List<Permission> permissionList = createTree(allPermissionList, "0");
        return permissionList;
    }

    //给角色分配权限
    @Override
    @Transactional
    public void saveRolePermissionRealtionShip(String roleId, String[] permissionIds) {

        rolePermissionService.remove(new QueryWrapper<RolePermission>().eq("role_id", roleId));

        List<RolePermission> rolePermissionList = new ArrayList<>();
        for (String permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId).setPermissionId(permissionId);

            rolePermissionList.add(rolePermission);
        }
        rolePermissionService.saveBatch(rolePermissionList);
    }

    //根据用户id获取按钮权限
    @Override
    public List<String> selectPermissionValueByUserId(String id) {

        List<String> selectPermissionValueList = null;
        if (this.isSysAdmin(id)) {
            //如果是系统管理员，获取所有权限
            selectPermissionValueList = baseMapper.selectAllPermissionValue();
        } else {
            selectPermissionValueList = baseMapper.selectPermissionValueByUserId(id);
        }
        return selectPermissionValueList;
    }

    @Override
    public List<JSONObject> selectPermissionByUserId(String userId) {
        List<Permission> selectPermissionList = null;
        if (this.isSysAdmin(userId)) {
            //如果是超级管理员，获取所有菜单
            selectPermissionList = baseMapper.selectList(null);
        } else {
            selectPermissionList = baseMapper.selectPermissionByUserId(userId);

            boolean flag = false;
            for (Permission p: selectPermissionList) {
                if ("1".equals(p.getId())){
                    flag = true;
                    break;
                }
            }
            if (!flag){
                QueryWrapper<Permission> wrapper = new QueryWrapper<>();
                wrapper.eq("id",1);
                // 添加权限表id为1 的权限
                selectPermissionList.add(baseMapper.selectOne(wrapper));
            }

        }

        List<Permission> permissionList = PermissionHelper.build(selectPermissionList);
        List<JSONObject> result = MenuHelper.build(permissionList);
        return result;
    }

    /**
     * 判断用户是否系统管理员
     *
     * @param userId
     * @return
     */
    private boolean isSysAdmin(String userId) {
        User user = userService.getById(userId);

        if (user != null && user.getUsername().equals("admin"))
            return true;
        return false;
    }

    //========================递归查询所有菜单================================================
    //获取全部菜单
    @Override
    public List<Permission> queryAllMenu() {
        //1 查询菜单表所有数据
        List<Permission> permissionList = baseMapper.selectList(null);
        //2 把查询所有菜单list集合按照要求进行封装
        List<Permission> resultList = PermissionHelper.build(permissionList);
//        List<Permission> resultList = createTree(permissionList, "0");
        return resultList;
    }

    //递归创建树形结构
    public List<Permission> createTree(List<Permission> lists, String pid) {
        List<Permission> tree = new ArrayList<>();
        for (Permission son : lists) {
            if (son.getPid().equals(pid)) {
                //将返回的 子节点数组 放到 父节点中
                son.setChildren(createTree(lists, son.getId()));
                //把当前对象放入数组
                tree.add(son);
            }
        }
        return tree;
    }

    //============递归删除菜单==================================
    @Override
    public void removeChildById(String id) {
        List<Permission> permissionList = baseMapper.selectList(null);
        deleteTree(permissionList, id);
    }

    //递归删除
    @Transactional
    public void deleteTree(List<Permission> lists, String pid) {
        for (Permission son : lists) {
            if (son.getPid().equals(pid)) {
                //递归删除
                deleteTree(lists, son.getId());
            }
        }
        baseMapper.deleteById(pid);
        //同时删除角色菜单表数据
        QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("permission_id", pid);
        rolePermissionService.remove(wrapper);
    }

}
